package app.framework.front.util;

import app.framework.constant.FrontConstants;
import jasmine.framework.common.util.CheckUtil;
import jasmine.framework.common.util.ErrorUtil;
import liquibase.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * <p>
 * 提供 WEB 相关的方法。
 * </p>
 *
 * @author mh.z
 */
public class WebUtil {

    /**
     * 返回去掉上下文路径的请求 URI
     *
     * @param request
     * @return
     */
    public static String getRequestUriWithoutContextPath(HttpServletRequest request) {
        CheckUtil.notNull(request, "request null");
        String returnUrl;

        String contextPath = request.getContextPath();
        String requestURI = request.getRequestURI();

        if (StringUtil.isEmpty(contextPath)) {
            returnUrl = requestURI;
        } else {
            returnUrl = requestURI.substring(contextPath.length());
        }

        return returnUrl;
    }

    /**
     * 设置响应体信息
     *
     * @param response
     * @param status
     * @param contentType
     */
    public static void setResponseInfo(HttpServletResponse response, int status, String contentType) {
        CheckUtil.notNull(response, "response null");

        response.setCharacterEncoding(FrontConstants.RESPONSE_CHARACTER_ENCODING);
        response.setStatus(status);
        response.setContentType(contentType);
    }

    /**
     * 写入数据到响应体
     *
     * @param response
     * @param data
     */
    public static void writeAndFlush(HttpServletResponse response, String data) {
        CheckUtil.notNull(response, "response null");

        if (data != null) {
            try {
                Writer writer = response.getWriter();
                writer.write(data);

                writer.flush();
            } catch (IOException e) {
                throw ErrorUtil.sneakyError(e);
            }
        }
    }

}
